package at.ac.thornwishstalon.ocrapp.ocr;

import java.io.File;
import java.util.ArrayList;

import android.graphics.Bitmap;
import android.graphics.Rect;
import android.graphics.RectF;
import android.os.Environment;
import android.util.Log;

import com.googlecode.tesseract.android.TessBaseAPI;

/**
 * 
 * @author fry
 *
 */
public class TesseractHelper {
	private static TesseractHelper instance=null;
	private final String TAG="TesseractHelper";

	private TessBaseAPI tessAPI;
	//private Bitmap currImage;

	private final String DATAPATH=Environment.getExternalStorageDirectory().getAbsolutePath()+"/OCRAPP";
	private final String LANG="eng+deu";

	public static final int DEFAULT=0;
	public static final int FAST=1;
	public static final int MODERATE=2; // don't! process chrashes ;)
	public static final int ACCURATE=3; // don't! process chrashes ;)


	private boolean debug=true;


	private int mode=DEFAULT;

	private TesseractHelper(){
		//initTesseract();
	}

	public static TesseractHelper getInstance(){
		if(instance==null)
			instance = new TesseractHelper();
		return instance;
	}

	public void initTesseract(int tmode){
		Log.d(TAG, "initialize ,mode: "+ tmode);
		try{
			this.mode=tmode;
			tessAPI = new TessBaseAPI();
			setMode(tmode);
			if(debug){
				tessAPI.setDebug(true);
			}
		}
		catch(Exception e){
			Log.e(TAG, e.getMessage());
		}
	}
	/**
	 * Set right image first!
	 * 
	 */
	public String doOcr(){
		//
		return tessAPI.getUTF8Text();
	}

	public void setImage(Bitmap bmp){

		tessAPI.setImage(bmp);

	}

	public void setImageFile(File bmp){
		tessAPI.setImage(bmp);
	}




	public void setRectangel(RectF rect){
		
		tessAPI.setRectangle(new Rect(
				Math.round(rect.left), 
				Math.round(rect.top), 
				Math.round(rect.right), 
				Math.round(rect.bottom)));

	}

	public void setMode(int mode){
		this.mode=mode;
		Log.d(TAG, "init");
		try{
			switch(this.mode){
			case FAST:{
				tessAPI.end();
				tessAPI.init(DATAPATH, LANG, TessBaseAPI.OEM_TESSERACT_ONLY);
				break;
			}
			case ACCURATE:{
				tessAPI.end();
				tessAPI.init(DATAPATH, LANG, TessBaseAPI.OEM_TESSERACT_CUBE_COMBINED);
				break;
			}
			case MODERATE:{
				tessAPI.end();
				tessAPI.init(DATAPATH, LANG, TessBaseAPI.OEM_CUBE_ONLY);
				break;
			}
			case DEFAULT:{
				tessAPI.end();
				tessAPI.init(DATAPATH, LANG, TessBaseAPI.OEM_DEFAULT);
				break;
			}

			}
		}
		catch(Exception e){
			//Log.e(TAG+ ", setMode: ", e.getMessage());
			Log.e(TAG, " setMode: "+ e.getMessage());
		}
	}

	public ArrayList<Rect> getWordRects(){
		return tessAPI.getWords().getBoxRects();
	}

	public ArrayList<Rect> getTextLines(){
		return tessAPI.getTextlines().getBoxRects();
	}

	public ArrayList<Rect> getRegions(){
		return tessAPI.getRegions().getBoxRects();
	}

	public int getTesseractMode(){
		return mode;
	}

	public void endTesseract(){
		tessAPI.end();
	}

	public String getText(){
		return tessAPI.getUTF8Text();
	}


}
